layui.define([], function(exports){
    const Demo = [
        {
            type: "form",
            pane: true,
            url: location.href,
            children: [
                [
                    {type: "text", title: "标题", name: "title", placeholder: "请输入标题",},
                    {type: "select", title: "分类", name: "status", options: this.assign.status_list, all: true}
                ],
                [
                    {type: "button", title: "分类列表", onClick: 'listCategory'},
                    {type: "button", title: "添加帮助", onClick: 'edit'},
                    {
                        type: "button",
                        title: "批量启用",
                        class: "layui-btn-primary",
                        onClick: 'batchStatus',
                        data: {table: "dataTable", value: 1,},
                    },
                    {
                        type: "button",
                        title: "批量禁用",
                        class: "layui-btn-primary",
                        onClick: 'batchStatus',
                        data: {
                            table: "dataTable",
                            value: 0,
                        },
                    },
                    {type: "submit", title: '<i class="layui-icon layui-icon-search"></i>搜索', onClick: 'search'}
                ]
            ],
        },
        {
            type: "table",
            elem: '#table',
            url: '',
            cols: [[
                {type: 'checkbox'}
                , {title: '标题', width: 150, field: 'title'}
                , {title: '排序号', width: 150, field: 'serial', edit: true, style: 'background-color:#cccccc;'}
                , {title: '时间', width: 250, templet: '<div>{{layui.util.toDateString(d.mtime * 1000)}}</div>'}
                , {
                    title: '状态', width: 200, templet: biz.builder([
                        {
                            type: "button",
                            title: "修改",
                            class: "layui-btn-xs layui-btn-primary",
                            onClick: "edit",
                            data: {
                                id: "{{d.id}}",
                            },
                        },
                        {
                            type: "button",
                            title: "启用",
                            class: "layui-btn-xs layui-btn-success",
                            onClick: "status",
                            data: {
                                field: "status",
                                id: "{{d.id}}",
                                value: 1
                            },
                            hidden: "{{d.status == 0?'hidden':''}}"
                        },
                        {
                            type: "button",
                            title: "禁用",
                            class: "layui-btn-xs layui-btn-danger",
                            onClick: "status",
                            data: {
                                field: "status",
                                id: "{{d.id}}",
                                value: 0
                            },
                            hidden: "{{d.status != 0?'hidden':''}}"
                        },
                        {
                            type: "button",
                            title: "删除",
                            class: "layui-btn-xs layui-btn-danger",
                            onClick: "del",
                            data: {id: "{{d.id}}",},
                        },
                    ])
                }
                , {
                    title: '操作', maxWidth: 300, templet: biz.builder([
                        {type: "badge", color: "green", text: "启用", hidden: "d.status==1"},
                        {type: "badge", color: "red", text: "禁用", hidden: "d.status==0"}
                    ])
                }
            ]],
            onEdit: 'tableEdit',
        }
    ];

    //所有组件
    const Components = {
        form: {
            default: {
                //提交的接口地址
                url: "form",
                //动态表达那规则
                rules: [],
                //操作按钮
                actions: [],
                //事件声明
                events: {},
            },
            render: function (config, events) {
                return new Promise(function (resolve) {
                    Promise.all([
                        //表单控件
                        new Promise(function (r) {
                            Promise.all(config.rules.map(function (rule) {
                                return new Promise(function (resolve) {
                                    //rules设置默认值
                                    rule = $.extend(true, {}, Components[rule.type].default, rule);
                                    Components[rule.type].render(rule, events).then(function (content) {
                                        //表单内容
                                        resolve("<div class='layui-form-item'>" + content + "</div>");
                                    });
                                });
                            })).then(function (contents) {
                                r(contents.join(''));
                            });
                        }),
                        //底部操作按钮
                        new Promise(function (r) {
                            Promise.all(config.actions.map(function (action) {
                                return new Promise(function (resolve) {
                                    //actions设置默认值
                                    action = $.extend(true, {}, Components[action.type].default, action);
                                    Components[action.type].render(action, events).then(function (content) {
                                        //表单内容
                                        resolve(content);
                                    });
                                });
                            })).then(function (contents) {
                                r("<div class='layui-form-item'><div class='layui-input-block'>" +
                                    contents.join('') +
                                    "</div></div>"
                                );
                            });
                        })
                    ]).then(function (res) {
                        resolve('<form class="layui-form">' + res.join('.') + "</form>");
                    });
                });
            },
        },
        table: {
            default: {
                elem: '#table'
                , url: '' //数据接口
                , page: false //开启分页
                , method: "post"
                , limit: 10
                , skin: 'line'
                , cols: [[]]
            },
            render: function (rule, events) {
                const target = "table";
                var interval = setInterval(function () {
                    if (!$().length) {
                        return;
                    }
                    clearInterval(interval);

                    layui.table.render(rule);

                    ['edit', 'toolbar', 'row', 'toll'].forEach(function (eventName) {
                        layui.table.on(eventName + '(' + target + ')', function (obj) {
                            events[eventName] && events[eventName](obj);
                        });
                    });
                }, 500);

                return new Promise(function (resolve) {
                    resolve('<table id="' + target + '" lay-filter="' + target + '"></table>');
                });
            }
        },
        text: {
            default: {
                type: "text",
                title: "单行文本",
                name: "text",
                input: "text",
                mid: "",
                min: "",
                max: "",
                maxlength: "",
                placeholder: "",
                value: "",
            },
            render: function (rule) {
                return new Promise(function (resolve) {
                    resolve(`
                        <div class="layui-inline" lay-block="${rule.name}">
                            <label class="layui-form-label">${rule.title}</label>
                            <div class="layui-input-inline">
                                <input 
                                    type="${rule.input}" 
                                    name="${rule.name}" 
                                    placeholder="${rule.placeholder}" 
                                    autocomplete="off" 
                                    class="layui-input"
                                    maxlength="${rule.maxlength}"
                                    min="${rule.min}"
                                    max="${rule.max}"
                                    value="${rule.value}">
                            </div>
                            <div class="layui-form-mid layui-word-aux">${rule.mid}</div>
                        </div>
                    `);
                });
            },
        },
        switch: {
            default: {
                type: "switch",
                title: "",
                name: "",
                options: [],
                value: "",
                //事件名
                event: undefined
            },
            render: function (rule, events) {
                return new Promise(function (resolve) {
                    var checked = rule.value ? "checked" : "";

                    //使用默认事件名
                    if (!rule.event) {
                        rule.event = 'change_' + rule.name;
                    }
                    //注册事件
                    if (!events[rule.event]) {
                        events[rule.event] = rule.handler;
                    }

                    resolve(`
                        <label class="layui-form-label">${rule.title}</label>
                        <div class="layui-inline">
                                <div class="layui-input-inline">
                                    <input type="checkbox"
                                           name="${rule.name}"
                                           lay-filter="${rule.event}"
                                           lay-skin="switch"
                                           lay-text="${rule.option[0]}|${rule.option[1]}"
                                           ${checked}
                                    >
                                </div>
                            </div>
                    `);
                });
            },
        },
        select: {
            default: {
                type: "select",
                title: "单选选择器",
                name: "select",
                options: {},
                mid: "",
                all: true,
                allText: "全部",
                allValue: "",
                //事件名称
                onChange: undefined,
            },
            render: function (rule, events) {
                return new Promise(function (resolve) {
                    var optionHtml = "";

                    if (rule.all) {
                        optionHtml += `<option value="${rule.allValue}">${rule.allText}</option>`;
                    }

                    Object.keys(rule.options).forEach(function (key) {
                        optionHtml += `<option value="${key}">${rule.options[key]}</option>`;
                    });

                    if (typeof rule.onChange == "function") {
                        //如果直接声明的回调函数则直接注册事件回调函数。
                        events["change_" + rule.name] = rule.onChange;
                        rule.onChange = "change_" + rule.name;
                    }

                    var interval = setInterval(function () {
                        if (!$("[name='" + rule.name + "']").length) {
                            return;
                        }
                        clearInterval(interval);

                        events["change_" + rule.name] && events["change_" + rule.name]({value: rule.value});
                    }, 100);

                    resolve(`
                        <div class="layui-inline" lay-block="${rule.name}">
                            <label class="layui-form-label">${rule.title}</label>
                            <div class="layui-input-inline">
                                <select name="${rule.name}" lay-filter="${rule.onChange}">${optionHtml}</select>
                            </div>
                            <div class="layui-form-mid layui-word-aux">${rule.mid}</div>
                        </div>
                    `);
                });
            },
        },
        row: {
            default: {
                children: [],
            },
            render: function (rule, events) {

            }
        },
        col: {
            default: {
                children: [],
            },
            render: function (rule, events) {

            },
        },
        blockquote: {
            default: {
                class: "",
                title: "",
                nm: false,
            },
            render: function (rule, events) {
                return new Promise(function (resolve) {
                    if (rule.nm) {
                        rule.class += " layui-quote-nm"
                    }
                    resolve(`<blockquote class="layui-elem-quote ${rule.class}">${rule.title}</blockquote>`);
                });
            },
        },
        fieldset: {
            default: {
                title: "",
                line:true,
                class:"",
                hrColor: "",
                children: [],
            },
            render: function (rule, events) {
                return new Promise(function(resolve){
                    if(rule.line){
                        rule.class += " layui-field-title";
                    }
                    resolve(`
                       <fieldset class="layui-elem-field ${rule.class}">
                          <legend>${rule.title}</legend>
                          <div class="layui-field-box">
                            ${content}
                          </div>
                        </fieldset>
                   `);
                });
            }
        },
        file: {
            default: {
                type: "file",
                //表单名
                name: "file",
                //image|file|video
                file: "file",
                //后缀
                ext: "*",
                //辅助文字
                mid: "",
                //同步为表单提交时上传文件，异步则使用独立上传接口上传
                async: true,
                //上传地址
                url: "",
                //异步上传参数名
                urlParamName: "file",
                //预览（仅视频、图片）
                preview: false,
                //进度条
                progress: false,
                //多文件上传，单文件false多文件具体数字
                multi: false,
            },
            render: function (rule, events) {
                return new Promise(function (resolve) {
                    var html, execute;
                    switch (rule.file) {
                        case "image":
                            if (rule.multi) {
                                html = `
                                    <div class="layui-inline" lay-block="${rule.name}">
                                        <label class="layui-form-label">${rule.title}</label>
                                        <div class="layui-input-inline">
                                            <div class="layui-upload">
                                                <button type="button" class="layui-btn" id="${rule.name}">多图片上传</button> 
                                                <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
                                                    预览图：
                                                    <div class="layui-upload-list" id="demo2_${rule.name}"></div>
                                                </blockquote>
                                            </div>
                                        </div>
                                    </div>
                                `;
                                execute = function () {

                                }
                            } else {
                                html = `
                                    <div class="layui-inline" lay-block="${rule.name}">
                                        <label class="layui-form-label">${rule.title}</label>
                                        <div class="layui-input-inline">
                                            <div class="layui-upload-drag" id="${rule.name}">
                                              <i class="layui-icon"></i>
                                              <p>点击上传，或将文件拖拽到此处</p>
                                              <div class="layui-hide" id="uploadDemoView_${rule.name}">
                                                <hr>
                                                <img src="${rule.value}" alt="上传成功后渲染" style="max-width: 196px">
                                              </div>
                                            </div>
                                             <div class="layui-form-mid layui-word-aux">${rule.mid}</div>
                                        </div>
                                    </div>
                                `
                                execute = function () {
                                    //拖拽上传
                                    layui.upload.render({
                                        elem: '#' + rule.name
                                        , url: rule.url
                                        , done: function (res) {
                                            layui.$('#uploadDemoView_' + rule.name)
                                                .removeClass('layui-hide')
                                                .find('img')
                                                .attr('src', res.files.file);
                                        }
                                    });
                                }
                            }
                            break;
                        case "video":

                            break;
                        case "file":
                            break;
                    }
                    var interval = setInterval(function () {
                        if (!$('#' + rule.name)) {
                            return;
                        }
                        clearInterval(interval);

                        execute();
                    }, 500);


                    resolve(html);
                });
            }
        },
        hidden: {
            default: {
                type: "hidden",
                name: "",
                value: "",
            },
            render: function (rule) {
                return new Promise(function (resolve, reject) {
                    resolve(`<input type="hidden" name="${rule.name}" value="${rule.value}">`);
                });
            }
        },
        textarea: {
            default: {
                type: "textarea",
                title: "多行文本",
                name: "",
                cols: 3,
                value: "",
                placeholder: "",
                onChange: undefined,
                onInput: undefined,
            },
            render: function (rule, events) {
                return new Promise(function (resolve) {
                    if (typeof rule.onChange == "function") {
                        //如果直接声明的回调函数则直接注册事件回调函数。
                        events["change_" + rule.name] = rule.onChange;
                        rule.onChange = "change_" + rule.name;
                    }
                    if (typeof rule.onInput == "function") {
                        //如果直接声明的回调函数则直接注册事件回调函数。
                        events["input_" + rule.name] = rule.onInput;
                        rule.onInput = "input_" + rule.name;
                    }

                    resolve(`
                        <div class="layui-form-item" lay-block="${rule.name}">
                            <label class="layui-form-label">${rule.title}</label>
                            <div class="layui-input-inline">
                                <textarea name="${rule.name}" 
                                    onchange="${rule.onChange}"
                                    oninput="${rule.onInput}"
                                    placeholder="${rule.placeholder}" 
                                    cols="${rule.cols}"
                                    class="layui-textarea">${rule.value}</textarea>
                            </div>
                        </div>
                    `);
                });
            },
        },
        editor: {
            default: {
                type: "editor",
                title: "富文本",
                name: "",
                height: "400px",
                width: "90%",
                value: "",
            },
            render: function (rule) {
                return new Promise(function (resolve) {
                    resolve(`
                        <div class="layui-form-item" lay-block="${rule.name}">
                            <label class="layui-form-label">${rule.title}</label>
                            <div class="layui-input-block">
                                <textarea style="padding-left:10px;width: ${rule.width};height: ${rule.height}" id="${rule.name}" name="${rule.name}">${rule.value}</textarea>
                                <script>window.UEDITOR_HOME_URL = "/static/js/editor/ueditor/";</script>
                                <script src="/static/js/editor/ueditor/ueditor.config.js"></script>
                                <script src="/static/js/editor/ueditor/ueditor.all.js"></script>
                                <script src="/static/js/editor/ueditor/plugins/135editor.js"></script>
                                <script type="text/javascript">
                                    var ue_${rule.name} = UE.ui.Editor({
                                        serverUrl:"upload?full_path=yes&thumb=no&from=${rule.name}",
                                        initialFrameHeight:500,
                                        initialFrameWidth:"100%",
                                        autoHeightEnabled:false
                                    });
                                    ue_${rule.name}.render("${rule.name}");
                                </script>
                            </div>
                        </div>
                    `);
                });
            },
        },
        submit: {
            default: {
                type: "submit",
                title: "提交",
                //自定义绑定的事件名
                event: undefined,
            },
            render: function (rule, events) {
                return new Promise(function (resolve) {
                    if (!events.submit) {
                        events.submit = rule.handler;
                    }
                    resolve(`<button type="button" lay-submit lay-filter="submit" class="layui-btn">${rule.title}</button>`);
                });
            }
        },
        reset: {
            default: {
                type: "reset",
                title: "重置",
            },
            render: function (rule, events) {
                return new Promise(function (resolve) {
                    if (!events.reset) {
                        events.reset = rule.handler;
                    }
                    resolve(`<button type="reset" lay-filter="reset" class="layui-btn layui-btn-primary">${rule.title}</button>`);
                });
            }
        },
        back: {
            default: {
                type: "back",
                title: "返回",
                onClick: undefined,
                handler: function () {
                    history.go(-1);
                }
            },
            render: function (rule, events) {
                return new Promise(function (resolve) {
                    if (!events.back) {
                        events.back = rule.handler;
                    }
                    resolve(`<button type="button" lay-filter="back" class="layui-btn layui-btn-primary">${rule.title}</button>`);
                });
            }
        },
        button: {
            default: {
                type: "button",
                title: "按钮",
                onClick: undefined,
                data: {},
            },
            render: function (rule, events) {
                return new Promise(function (resolve) {
                    if (!events['click_' + rule.name]) {
                        events['click_' + rule.name] = rule.handler;
                    }
                    resolve(`<button type="button" lay-filter="click_${rule.name}" class="layui-btn layui-btn-primary">${rule.title}</button>`);
                });

            }
        },
        template: {
            default: {
                type: "template",
                value: {},
                template: "",
            },
            render: function (rule) {
                return new Promise(function (resolve) {
                    layui.laytpl($(rule.template).html() || "").render(rule.value, function (html) {
                        resolve(`<div lay-block="${rule.name}">${html}</div>`);
                    });
                });
            }
        }
    };

    exports('builder', function(){

    });
});